package com.lanyam.travel.base.service.impl;

import com.lanyam.travel.base.dao.statistics.BaseDataStatisticsMapper;
import com.lanyam.travel.base.dao.statistics.TravelOrderDataStatisticsMapper;
import com.lanyam.travel.base.entity.DataStatistics;
import com.lanyam.travel.base.entity.User;
import com.lanyam.travel.base.service.IDataStatisticsService;
import com.lanyam.travel.base.service.UserService;
import com.lanyam.travel.base.utils.DataStatisticsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 版权所有： 稻草人
 * 创建者： wenhe
 * 创建时间: 2020-02-04
 * 描述：
 * 其它：
 **/
@Service
public class DataStatisticsServiceImpl implements IDataStatisticsService {

    @Autowired
    private WebApplicationContext webApplicationContext;
    @Autowired
    private UserService userService;
    @Autowired
    private TravelOrderDataStatisticsMapper travelOrderDataStatisticsMapper;

    /**
     * 需要调用的mapper的后缀
     */
    private String mapperSuffixt = "DataStatisticsMapper";

    @Override
    public Map getDataStatistics(DataStatistics dataStatistics) {
        BaseDataStatisticsMapper mapper = (BaseDataStatisticsMapper) webApplicationContext.getBean(dataStatistics.getMapperName() + mapperSuffixt);
        Map<String, Object> queryParams = dataStatistics.getQueryParams();
        // 设置当前登录用户信息
        User currentUser = userService.getCurrentUser();
        if (currentUser != null) {
            if (currentUser.getRoleId() != null && currentUser.getRoleId().equals("2")) {
                queryParams.put("roleType", "admin");
            } else {
                queryParams.put("roleType", "notAdmin");
                queryParams.put("loginUser", currentUser.getId());
            }
        }
        // 查询数据
        List<Map> queryResult = mapper.getDataStatistics(dataStatistics.getDimension(), queryParams);
        Map dataStatisticsMap = DataStatisticsUtil.transform(dataStatistics.getChartType(), queryResult);
        return dataStatisticsMap;
    }

    @Override
    public Map getOrderCount() {
        List<Map> orderCount = travelOrderDataStatisticsMapper.getOrderCount();
        Map map = new HashMap();
        for (Map m: orderCount) {
            map.put(m.get("name"), m.get("count")==null?0:m.get("count"));
        }
        return map;
    }
}
